//
//  QSendingMapVC.m
//  QoilPublic
//
//  Created by 杨凯 on 2017/8/4.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "QSendingMapVC.h"
#import "QMapModel.h"
#import "QDetailNoteOrderCell.h"
#import "QDetailPeopleCell.h"
#import "QDetailsOrderMapCell.h"
@interface QSendingMapVC ()<MAMapViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    CLLocationCoordinate2D coords1[5];
    NSArray *moveArr;
    BOOL _first;
    BOOL _moveOver;
    NSTimer *_timer;
    CGFloat _totalTime;
    CGFloat _speed;
    NSInteger a;
    
    NSMutableArray *layerArr;
    
    NSMutableArray *speedArr;
    
    QMapModel *beforeModel;
    
    QDetailNoteOrderCell *_noteCell;
    
    BOOL _show;
    
    UIButton *phonebutton;//联系司机
    
    UIControl * _maskView;
    
    UIButton *navButton;//查看订单
}
@property(nonatomic,strong) MAMapView *mapView;
@property (nonatomic, strong) MAAnimatedAnnotation* annotation;
@property(nonatomic,strong)UITableView *tableView;

@end

@implementation QSendingMapVC

- (id)init{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"配送地图";
    
    _first = YES;
    _moveOver = YES;
    _show = NO;
    beforeModel.lat = 0.00;
    beforeModel.lng = 0.00;
    layerArr = [[NSMutableArray alloc] init];
    
    speedArr = [NSMutableArray arrayWithCapacity:4];
    [self createUi];
    
    [self requestData];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(requestData) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

    [self createTableView];
    
    [self requestDetailData:self.orderId];


}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_timer invalidate];
    _timer = nil;
    CLog(@"释放了");

}

- (void)dealloc{
    [_timer invalidate];
    _timer = nil;
    CLog(@"释放了");
}

- (void)createUi{
    
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.delegate = self;
    
    [self.view addSubview:self.mapView];
    
    self.annotation = [[MAAnimatedAnnotation alloc] init];
    
}

- (void)createTableView{
    
    navButton = [UIButton buttonWithType:UIButtonTypeCustom];
    navButton.frame = CGRectMake(0,0,80, 45);
    navButton.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    navButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [navButton setTitle:@"查看订单" forState:UIControlStateNormal];
    [navButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [navButton addTarget:self action:@selector(OrderAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:navButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    _maskView = [[UIControl alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight)];
    _maskView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.00];
    _maskView.hidden = YES;
    [self.view addSubview:_maskView];

    [_maskView addTarget:self action:@selector(OrderAction) forControlEvents:UIControlEventTouchUpInside];
    
    UIView * _whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    _whiteView.backgroundColor = [UIColor whiteColor];
    
    UILabel *label = [QViewUtility createLabelWithFrame:CGRectMake(15, 5, 80, 40) font:Ksize16 textAlignment:NSTextAlignmentLeft textColor:[UIColor blackColor] text:@"订单状态"];
    [_whiteView addSubview:label];
    
    UILabel *sublabel = [QViewUtility createLabelWithFrame:CGRectMake(label.right+5, 5, 80, 40) font:Ksize15 textAlignment:NSTextAlignmentLeft textColor:[QColorUtility defaultBlueColor] text:@"配送中"];
    [_whiteView addSubview:sublabel];


    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_maskView addSubview:_tableView];
    
    _tableView.frame = CGRectMake(0, 250, kScreenWidth, kScreenHeight - 250);
    
    _tableView.tableHeaderView = _whiteView;
    
    [_tableView registerNib:[UINib nibWithNibName:@"QDetailsOrderMapCell" bundle:nil] forCellReuseIdentifier:@"QDetailsOrderMapCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QDetailNoteOrderCell" bundle:nil] forCellReuseIdentifier:@"QDetailNoteOrderCell"];
    
    _noteCell = [_tableView dequeueReusableCellWithIdentifier:@"QDetailNoteOrderCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QDetailPeopleCell" bundle:nil] forCellReuseIdentifier:@"QDetailPeopleCell"];
    
    phonebutton = [QViewUtility createButtonWithFrame:CGRectZero font:17 title:@"联系司机" titleColor:[UIColor whiteColor] backgroundColor:[QColorUtility defaultBlueColor]];
    [phonebutton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:phonebutton];
//    WS(wSelf);
//    [phonebutton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(wSelf.view.mas_left).offset(0);
//        make.right.equalTo(wSelf.view.mas_right).offset(0);
//        make.bottom.equalTo(wSelf.view.mas_bottom).offset(0);
//        make.height.equalTo(@45);
//    }];
//    phonebutton.hidden = YES;
    phonebutton.frame = CGRectMake(0, 0, kScreenWidth, 45);
    _tableView.tableFooterView = phonebutton;
    
    
    
}

- (void)buttonAction:(UIButton *)btn{
    CLog(@"联系司机");
    [QViewUtility showPhonePlayBoxViewWithName:_model.name Number:_model.tankerTel myBlock:^(NSInteger index) {
        if(index == 1){
            [QViewUtility callPhoneWithNumber:_model.tankerTel];
        }
        
    }];
}


- (void)OrderAction{
    if (_show == YES) {
        _show = NO;
    }else{
        _show = YES;
    }
    
    if (_show == YES) {
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
            [navButton setTitle:@"关闭订单" forState:UIControlStateNormal];
            _maskView.frame = CGRectMake(1, 0, kScreenWidth - 2, kScreenHeight);
            _maskView.hidden = NO;
        } completion:^(BOOL finished) {
            
        }];

    }else{
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.6 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
            [navButton setTitle:@"查看订单" forState:UIControlStateNormal];
            _maskView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);
            _maskView.hidden = YES;
            
        } completion:^(BOOL finished) {
            
        }];

    }
}



- (void)requestData{
    
    
    NSString *url = [QParamService urlWithAction:@"map/getPosition"];
    NSDictionary *param = [QParamService getPositionWithCarNumber:_carLicenseNumer];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            QMapModel *mapModel = [QMapModel objectFromDict:basModel.items];
            
            [speedArr addObject:mapModel];
            
            if (_first) {
                a = 0;
                
                coords1[0].latitude = mapModel.lat;
                coords1[0].longitude = mapModel.lng;

                self.annotation.coordinate = coords1[0];
                [self.mapView addAnnotation:self.annotation];
                MACoordinateSpan span = {0.01,0.01};
                MACoordinateRegion region = {coords1[0],span};
                [self.mapView setRegion:region animated:YES];
                _first = NO;

            }else{
                if (mapModel.lat != beforeModel.lat || mapModel.lng != beforeModel.lng) {
                    a ++;
                    coords1[a].latitude = mapModel.lat;
                    coords1[a].longitude = mapModel.lng;

                }
                
                beforeModel = mapModel;
                
                if (a>=4 && _moveOver == YES) {
                    
                    MAPolyline *polyline1 = [MAPolyline polylineWithCoordinates:coords1 count:sizeof(coords1) / sizeof(coords1[0])];
                    
                    [layerArr addObject:polyline1];
                    
                    [self.mapView addOverlays:layerArr];

                    _moveOver = NO;
                    CLLocation *location = [[CLLocation alloc] initWithLatitude:coords1[0].latitude longitude:coords1[0].longitude];
                    
                    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:coords1[a].latitude longitude:coords1[a].longitude];

                    
                    CLLocationDistance meters=[location distanceFromLocation:location1];
                    
                    for (QMapModel *mapModel in speedArr) {
                        _speed = _speed + mapModel.veo;
                    }
                    
                    _speed = _speed/4;
                    

                    _totalTime = (meters/1000)/_speed *3600;
                    
                    self.annotation.title = @"油到了~";
                    
                    
                    if (_totalTime > 0) {
                        _speed = 0.00;
                        [speedArr removeAllObjects];
                        [self startMove];

                    }
                    
                    a = -1;
                }
                

            }
            
        }
    }];

}

- (void)startMove{
    
    [self.annotation addMoveAnimationWithKeyCoordinates:coords1 count:sizeof(coords1) / sizeof(coords1[0]) withDuration:_totalTime withName:nil completeCallback:^(BOOL isFinished) {
        _moveOver = YES;
        _totalTime = 0.00;
    }];
}

#pragma mark - mapview delegate
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[MAPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithOverlay:overlay];
        polylineRenderer.lineWidth    = 7.f;
        [polylineRenderer loadStrokeTextureImage:[UIImage imageNamed:@"arrowTexture"]];
        return polylineRenderer;
        
    }
    
    return nil;
}


- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[MAUserLocation class]]) {
       
            MAPinAnnotationView *annotationView = nil;
            if (annotationView == nil)
            {
                annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
                
//                UIImage *imge  =  [UIImage imageNamed:@"Annotation_Car"];
//                annotationView.image =  imge;

            }
//            annotationView.pinColor = MAPinAnnotationColorRed;
        
            //annotationView.canShowCallout= YES;       //设置气泡可以弹出，默认为NO
//            annotationView.animatesDrop = NO;        //设置标注动画显示，默认为NO
//            annotationView.draggable = YES;        //设置标注可以拖动，默认为NO
            return annotationView;
    }else{
        NSString *pointReuseIndetifier = @"myReuseIndetifier";
        MAAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                          reuseIdentifier:pointReuseIndetifier];
            
            UIImage *imge  =  [UIImage imageNamed:@"Annotation_Car"];
            annotationView.image =  imge;
        }

        annotationView.canShowCallout               = NO;
        annotationView.draggable                    = NO;
        annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        
        return annotationView;

    }
    
    return nil;
   
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(section == 0){
        return 7;
    }else if (section == 2){
        return 2;
    }
    else if(section == 3){
        return 2;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 1){
        QDetailNoteOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDetailNoteOrderCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(_model){
            cell.model = _model;
        }
        return cell;
    }else if(indexPath.section == 3){
        QDetailPeopleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDetailPeopleCell" forIndexPath:indexPath];
        cell.isSend = YES;
        cell.indexPath = indexPath;
        if(_model){
            cell.model = _model;
        }
        
        return cell;
    }else{
        QDetailsOrderMapCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDetailsOrderMapCell" forIndexPath:indexPath];
        cell.indexPath = indexPath;
        if(_model){
            cell.model = _model;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 1){
        if(_model){
            _noteCell.model = _model;
        }
        CGFloat h = [_noteCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height+1;
        return h;
    }else{
        return 50;
    }
    
}




- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // 开启定位
    NSArray * arr = [NSArray arrayWithObject:self.annotation];
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    [self.mapView showAnnotations:arr edgePadding:UIEdgeInsetsMake(200, 100, 200, 200) animated:YES];

}

#pragma mark --- 订单详情
- (void)requestDetailData:(NSString *)orderId{
    NSString *url = [QParamService urlWithAction:@"/order/userOrderDetail"];
    NSDictionary *param = [QParamService detailOrderid:orderId];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        _carLicenseNumer = @"";
        NSDictionary *tmpDic = [dict objectForKey:@"items"];
        _carLicenseNumer = [tmpDic objectForKey:@"carNumber"];
        if([basModel.result isEqualToString:@"success"]){
            _model = [QAllorderListModel objectFromDict:basModel.items];
            [_tableView reloadData];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
